import React, { useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';

import { getCinemaList } from '../redux/action/CinemaActionCreator';

const useCinemaList = (props) => {
  const { cityId, cityName, list, getCinemaList } = props;

  useEffect(() => {
    list.length === 0 && getCinemaList(cityId);
    return () => {};
  }, [cityId, list.length, getCinemaList]);

  return {
    cityName,
    list,
  };
};

const Cinema = (props) => {
  const { cityName, list } = useCinemaList(props);

  const navigate = useNavigate();

  const handleClick = useCallback(() => {
    navigate('/city');
  }, [navigate]);

  return (
    <div>
      <div onClick={handleClick}>{cityName}</div>
      <ul>
        {list.map((item) => {
          return <li key={item.cinemaId}>{item.name}</li>;
        })}
      </ul>
    </div>
  );
};

const MapStateToPropsParam = (state) => {
  let { id: cityId, name: cityName } = state.CityReducer.city;
  let { cinemaList: list } = state.CinemaReducer;
  return {
    cityId,
    cityName,
    list,
  };
};

const MapDispatchToPropsParam = {
  getCinemaList,
};

export default connect(MapStateToPropsParam, MapDispatchToPropsParam)(Cinema);
